package com.yjt.fresh.adpater.adpsection;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.activity.AtyCart;
import com.yjt.fresh.activity.AtyGetCoupon;
import com.yjt.fresh.activity.AtyProductDetail;
import com.yjt.fresh.api.ApiAlterGoodsCount;
import com.yjt.fresh.bean.BeanCart;
import com.yjt.fresh.bean.BeanCartChange;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.PreferenceManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车适配器
 * Created by mcc on 2018-07-30.
 */

public class AdpRvAtyCart extends SectionedRecyclerViewAdapter<AdpRvAtyCartHeaderHolder, AdpRvAtyCartContentHolder, RecyclerView.ViewHolder> {
    public static final int CHILD_GOODS_SELECT = 1001;
    public static final int STORE_SELECT = 1002;
    private List<BeanCartChange> mBeanCartChanges;
    private Activity mContext;

    public List<BeanCartChange> getBeanCartChanges() {
        return mBeanCartChanges;
    }

    public void setNewData(List<BeanCartChange> beanCartChangeList) {
        mBeanCartChanges = new ArrayList<>();
        mBeanCartChanges.addAll(beanCartChangeList);
        notifyDataSetChanged();
    }

    public AdpRvAtyCart(Activity context, List<BeanCartChange> beanCartChanges) {
        mBeanCartChanges = beanCartChanges;
        mContext = context;
    }

    @Override
    protected int getSectionCount() {
        return mBeanCartChanges.size();
    }

    @Override
    protected int getItemCountForSection(int section) {
        return mBeanCartChanges.get(section).getBeanCarts().size();
    }

    @Override
    protected boolean hasFooterInSection(int section) {
        return false;
    }

    @Override
    protected AdpRvAtyCartHeaderHolder onCreateSectionHeaderViewHolder(ViewGroup parent, int viewType) {
        return new AdpRvAtyCartHeaderHolder(View.inflate(mContext, R.layout.app_recycle_item_aty_cart_head, null));
    }

    @Override
    protected RecyclerView.ViewHolder onCreateSectionFooterViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    protected AdpRvAtyCartContentHolder onCreateItemViewHolder(ViewGroup parent, int viewType) {
        return new AdpRvAtyCartContentHolder(View.inflate(mContext, R.layout.app_recycle_item_aty_cart_content, null));
    }

    @Override
    protected void onBindSectionHeaderViewHolder(AdpRvAtyCartHeaderHolder holder, final int section) {
        CheckBox cbHeader = holder.getCbHeader();
        ImageView ivStoreType = holder.getIvStoreType();
        TextView tvStoreName = holder.getTvStoreName();
        TextView tvGetCoupon = holder.getTvGetCoupon();
        if (mBeanCartChanges.get(section).getStoreName() != null) {
            tvStoreName.setText(mBeanCartChanges.get(section).getStoreName());
            if ("de8645357d7444179e2c960fc2e68353".equals(mBeanCartChanges.get(section).getBeanCarts().get(0).getSTORE_ID())) {
                ivStoreType.setImageResource(R.mipmap.e1_ci_zy);
            } else {
                ivStoreType.setImageResource(R.mipmap.e1_ci_05);
            }
            tvGetCoupon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, AtyGetCoupon.class);
                    intent.putExtra(MyConstants.STORE_ID, mBeanCartChanges.get(section).getBeanCarts().get(0).getSTORE_ID());
                    mContext.startActivity(intent);
                }
            });
            cbHeader.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    BeanCartChange beanCartChange = mBeanCartChanges.get(section);
                    beanCartChange.setCheck(isChecked);
                    List<BeanCart> beanCarts = beanCartChange.getBeanCarts();
                    for (int i = 0; i < beanCarts.size(); i++) {
                        beanCarts.get(i).setCheck(isChecked);
                    }
                    specialUpdate();
                    if (mOnSectionItemClickListener != null) {
                        mOnSectionItemClickListener.onSectionItemClick(STORE_SELECT, section, -1, 0, null, null);
                    }
                }
            });
            cbHeader.setChecked(mBeanCartChanges.get(section).isCheck());
        } else {
            cbHeader.setVisibility(View.GONE);
            ivStoreType.setVisibility(View.GONE);
            tvGetCoupon.setVisibility(View.GONE);
            tvStoreName.setText("失效商品");
        }
    }

    @Override
    protected void onBindSectionFooterViewHolder(RecyclerView.ViewHolder holder, int section) {

    }

    @Override
    protected void onBindItemViewHolder(AdpRvAtyCartContentHolder holder, final int section, final int position) {
        CheckBox cbContent = holder.getCbContent();
        ImageView ivContent = holder.getIvContent();
        TextView tvTitle = holder.getTvTitle();
        TextView tvType = holder.getTvType();
        final TextView tvCount = holder.getTvCount();
        LinearLayout llCount = holder.getLlCount();
        TextView tvNewPrice = holder.getTvNewPrice();
        TextView tvOldPrice = holder.getTvOldPrice();
        RelativeLayout rlOldPrice = holder.getRlOldPrice();
        View vBottom = holder.getVBottom();
        ImageView ivSub = holder.getIvSub();
        ImageView ivAdd = holder.getIvAdd();

        ivSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer count = Integer.valueOf(tvCount.getText().toString());
                if (count > 1){
                    count --;
                    String childgoods_id = mBeanCartChanges.get(section).getBeanCarts().get(position).getGOODINFO().getCHILDGOODS_ID();
                    alterGoodsCount(count,childgoods_id,tvCount,section,position);
                }
            }
        });

        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int stock = mBeanCartChanges.get(section).getBeanCarts().get(position).getGOODINFO().getSTOCK();
                Integer count = Integer.valueOf(tvCount.getText().toString());
                if (count < stock){
                    count ++;
                    String childgoods_id = mBeanCartChanges.get(section).getBeanCarts().get(position).getGOODINFO().getCHILDGOODS_ID();
                    alterGoodsCount(count,childgoods_id,tvCount,section,position);
                }
            }
        });
        if (mBeanCartChanges.get(section).getBeanCarts().size() - 1 == position) {
            vBottom.setVisibility(View.GONE);
        }
        BeanCart.GOODINFOBean goodInfo = mBeanCartChanges.get(section).getBeanCarts().get(position).getGOODINFO();
        if (goodInfo != null) {
            Glide.with(mContext).load(goodInfo.getSKU_IMG()).into(ivContent);
            tvTitle.setText(goodInfo.getTITLE());
            String oneSpecContent = goodInfo.getONE_SPEC_CONTENT();
            String twoSpecContent = goodInfo.getTWO_SPEC_CONTENT();
            String typeOne = oneSpecContent == null ? "" : oneSpecContent;
            String typeTwo = twoSpecContent == null ? "" : twoSpecContent;
            tvType.setText(typeOne + ";" + typeTwo);

            tvCount.setText(mBeanCartChanges.get(section).getBeanCarts().get(position).getCOUNT() + "");
            tvNewPrice.setText(goodInfo.getSINGLE_PRICE() + "");
            tvOldPrice.setText("¥ 0.00");

            cbContent.setChecked(mBeanCartChanges.get(section).getBeanCarts().get(position).isCheck());

            cbContent.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mBeanCartChanges.get(section).getBeanCarts().get(position).setCheck(isChecked);
                    if (mOnSectionItemClickListener != null) {
                        mOnSectionItemClickListener.onSectionItemClick(CHILD_GOODS_SELECT, section, position, 0, null, null);
                    }
                }
            });


            holder.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, AtyProductDetail.class);
                    intent.putExtra(MyConstants.GOODS_ID, mBeanCartChanges.get(section).getBeanCarts().get(position).getGOODINFO().getGOODS_ID());
                    mContext.startActivity(intent);
                }
            });
        } else {
            tvCount.setVisibility(View.GONE);
            tvNewPrice.setVisibility(View.GONE);
            tvOldPrice.setVisibility(View.GONE);
            cbContent.setVisibility(View.GONE);
            llCount.setVisibility(View.GONE);
            rlOldPrice.setVisibility(View.GONE);
        }
    }

    private void alterGoodsCount(final Integer count, String childgoods_id, final TextView tvCount, final int section, final int position) {
        ApiAlterGoodsCount apiAlterGoodsCount = new ApiAlterGoodsCount(new HttpOnNextListener<BaseResultEntity>() {
            @Override
            public void onNext(BaseResultEntity baseResultEntity) {
                mBeanCartChanges.get(section).getBeanCarts().get(position).setCOUNT(count);
                tvCount.setText(count+"");
            }

            @Override
            public void onReLogin() {

            }
        },mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        map.put("CHILDGOODS_ID",childgoods_id);
        map.put("COUNT",count);
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiAlterGoodsCount.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiAlterGoodsCount);
    }

    private void specialUpdate() {
        Handler handler = new Handler();
        final Runnable r = new Runnable() {
            public void run() {
                notifyDataSetChanged();
            }
        };
        handler.post(r);
    }

    private OnSectionItemClickListener mOnSectionItemClickListener;

    public void setOnSectionItemClickListener(OnSectionItemClickListener onSectionItemClickListener) {
        mOnSectionItemClickListener = onSectionItemClickListener;
    }
}
